const fs = require('fs');
const path = require('path');
const axios = require('axios');
const { execSync } = require('child_process');
const { PATH_CONFIG } = require('../config/constants');
const AdmZip = require('adm-zip');

// FFmpeg 配置
const FFMPEG_CONFIG = {
    windows: {
        url: 'https://www.gyan.dev/ffmpeg/builds/ffmpeg-release-essentials.zip',
        binaryName: 'ffmpeg.exe',
        version: 'release-essentials'
    },
    linux: {
        url: 'https://johnvansickle.com/ffmpeg/releases/ffmpeg-release-amd64-static.tar.xz',
        binaryName: 'ffmpeg',
        version: 'release-amd64-static'
    }
};

// 获取平台特定的目录路径
function getPlatformPaths() {
    const platform = process.platform === 'win32' ? 'windows' : 'linux';
    const version = FFMPEG_CONFIG[platform].version;
    const downloadDir = path.join(PATH_CONFIG.ffmpegDir, 'downloads');
    const extractDir = path.join(PATH_CONFIG.ffmpegDir, 'extracted', platform, version);
    const zipPath = path.join(downloadDir, `ffmpeg-${version}.zip`);
    const ffmpegPath = path.join(extractDir, FFMPEG_CONFIG[platform].binaryName);
    
    return {
        platform,
        downloadDir,
        extractDir,
        zipPath,
        ffmpegPath
    };
}

// 检查 FFmpeg 是否已安装
async function checkFFmpeg() {
    try {
        const { platform, extractDir } = getPlatformPaths();
        const ffmpegPath = path.join(extractDir, FFMPEG_CONFIG[platform].binaryName);
        
        console.log(`检查 FFmpeg: ${ffmpegPath}`);
        
        if (!fs.existsSync(extractDir)) {
            console.log('FFmpeg 目录不存在');
            return false;
        }

        if (fs.existsSync(ffmpegPath)) {
            try {
                const output = execSync(`"${ffmpegPath}" -filters | findstr xfade`).toString();
                if (output.includes('xfade')) {
                    console.log('✅ FFmpeg 已安装且支持 xfade');
                    return true;
                }
            } catch (error) {
                console.log('❌ FFmpeg 检查失败:', error.message);
            }
        }
        
        return false;
    } catch (error) {
        console.log('❌ FFmpeg 检查失败:', error.message);
        return false;
    }
}

// 下载 FFmpeg
async function downloadFFmpeg() {
    const { platform, downloadDir, zipPath } = getPlatformPaths();
    const config = FFMPEG_CONFIG[platform];
    
    try {
        console.log(`开始下载 FFmpeg (${platform})...`);
        console.log(`下载地址: ${config.url}`);
        
        // 确保下载目录存在
        if (!fs.existsSync(downloadDir)) {
            fs.mkdirSync(downloadDir, { recursive: true });
        }

        const response = await axios({
            url: config.url,
            method: 'GET',
            responseType: 'stream',
            timeout: 30000,
            maxContentLength: 100 * 1024 * 1024,
            headers: {
                'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
            },
            onDownloadProgress: (progressEvent) => {
                if (progressEvent.total) {
                    const progress = (progressEvent.loaded / progressEvent.total * 100).toFixed(2);
                    console.log(`下载进度: ${progress}% (${(progressEvent.loaded / 1024 / 1024).toFixed(2)} MB / ${(progressEvent.total / 1024 / 1024).toFixed(2)} MB)`);
                }
            }
        });

        const writer = fs.createWriteStream(zipPath);
        response.data.pipe(writer);

        await new Promise((resolve, reject) => {
            writer.on('finish', resolve);
            writer.on('error', reject);
        });

        console.log('下载完成，开始解压...');
        return await extractFile(zipPath);
    } catch (error) {
        console.error('❌ FFmpeg 下载失败:', error.message);
        console.log('临时文件保留在:', zipPath);
        return false;
    }
}

// 解压文件
async function extractFile(zipPath) {
    try {
        const { platform, extractDir } = getPlatformPaths();
        console.log(`开始解压: ${zipPath}`);
        
        // 确保解压目录存在
        if (!fs.existsSync(extractDir)) {
            fs.mkdirSync(extractDir, { recursive: true });
        }

        const zip = new AdmZip(zipPath);
        const entries = zip.getEntries();
        console.log(`压缩包包含 ${entries.length} 个文件`);

        let extractedCount = 0;
        for (const entry of entries) {
            if (!entry.isDirectory) {
                console.log(`解压: ${entry.entryName}`);
                zip.extractEntryTo(entry.entryName, extractDir, false, true);
                extractedCount++;
                console.log(`进度: ${(extractedCount / entries.length * 100).toFixed(2)}%`);
            }
        }

        // 查找并移动 ffmpeg.exe
        const findFFmpeg = (dir) => {
            const files = fs.readdirSync(dir);
            for (const file of files) {
                const fullPath = path.join(dir, file);
                if (fs.statSync(fullPath).isDirectory()) {
                    const found = findFFmpeg(fullPath);
                    if (found) return found;
                } else if (file === FFMPEG_CONFIG[platform].binaryName) {
                    return fullPath;
                }
            }
            return null;
        };

        const ffmpegPath = findFFmpeg(extractDir);
        if (ffmpegPath) {
            const targetPath = path.join(extractDir, FFMPEG_CONFIG[platform].binaryName);
            if (ffmpegPath !== targetPath) {
                fs.copyFileSync(ffmpegPath, targetPath);
            }
            return true;
        }
        
        throw new Error(`未找到 ${FFMPEG_CONFIG[platform].binaryName}`);
    } catch (error) {
        console.error('解压失败:', error.message);
        return false;
    }
}

// 初始化 FFmpeg
async function initFFmpeg() {
    try {
        console.log('开始初始化 FFmpeg...');
        
        if (await checkFFmpeg()) {
            console.log('✅ FFmpeg 已正确安装');
            return true;
        }
        
        const { extractDir } = getPlatformPaths();
        
        // 清理旧文件
        if (fs.existsSync(extractDir)) {
            console.log('清理旧文件...');
            fs.rmSync(extractDir, { recursive: true, force: true });
        }

        const success = await downloadFFmpeg();
        
        if (!success) {
            throw new Error('FFmpeg 安装失败');
        }

        console.log('✅ FFmpeg 初始化完成');
        return true;
    } catch (error) {
        console.error('❌ FFmpeg 初始化失败:', error.message);
        return false;
    }
}

module.exports = {
    initFFmpeg,
    checkFFmpeg
}; 